package org.xingole.algo.dp;

/**
 * <p>
 * A class that provides a solution to the abbreviation problem.
 * 
 * <p>
 * Problem: Given two strings, {@code a} and {@code b}, determine
 * if string {@code a} can be transformed into string {@code b} by
 * performing the following operations:
 * 
 * <ol>
 *      <li>Capitalize zero or more of {@code a}'s lowercase letters
 * (i.e, convert them to uppercase).</li>
 *     <li>Delete any of the remaining lowercase letters from
 * {@code a}.</li>
 * 
 * <p>
 * The task is to determine whether it is possible to make string
 * {@code a} equal to string {@code b}.
 * 
 * @author xingole
 */
public class Abbreviation {
    private Abbreviation() {}

    /**
     * Determines if string {@code a} can be transformed into string
     * {@code b} by capitalizing some of its lowercase letters and
     * deleting the rest.
     * 
     * @param a The input string which may contain both uppercase and
     * lowercase letters.
     * @param b The target string containing only uppercase letters.
     * @return {@code true} if string {@code a} can be transformed into
     * string {@code b}, {@code false} otherwise.
     * 
     * @apiNote Time Complexity: O(n*m), where n is the length of string {@code a}
     * and m is the length of string {@code b}.
     * @apiNote Space Complexity: O(n*m) due to the dynamic programming table.
     */
    public static boolean abbr(String a, String b) {
        int n = a.length();
        int m = b.length();

        // Create a 2D DP table where dp[i][j] indicates whether
        // the first i characters of a can be transformed to the
        // first j characters of b.
        boolean[][] dp = new boolean[n + 1][m + 1];

        // Base case: empty strings
        dp[0][0] = true;

        // State transition
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= m; j++) {
                if (dp[i][j]) {
                    // Case 1: If the current characters match (or can be capitalized to match)
                    if (j < m && Character.toUpperCase(a.charAt(i)) == b.charAt(j)) {
                        dp[i + 1][j + 1] = true;
                    }

                    // Case 2: If the character in a is lowercase, we can skip it
                    if (Character.isLowerCase(a.charAt(i))) {
                        dp[i + 1][j] = true;
                    }
                }
            }
        }

        return dp[n][m];
    }

    public static void main(String[] args) {
        String a = "daBcd";
        String b = "ABC";
        boolean result = abbr(a, b);
        System.out.println("Can \"" + a + "\" be abbreviated to \"" + b + "\"? " + result);
    }
}
